<template>
  <a-modal
    v-model:open="visible"
    :title="modalTitle"
    :width="modelWidth"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirmLoading="confirmLoading"
  >
    <a-row :gutter="24" style="justify-content: center; margin-top: 20px">
      <a-form
        :model="formState"
        :rules="rules"
        layout="inline"
        ref="formRef"
        :labelCol="{
          style: {
            width: '120px',
          },
        }"
        :labelWrap="true"
        :labelAlign="'right'"
        style="width: 100%"
      >
        <a-col :span="8">
          <a-form-item label="电站名称：" name="stationId">
            <a-select
              v-model:value="formState.stationId"
              class="formSelect"
              placeholder="请选择"
              show-search
              optionFilterProp="label"
              allow-clear
              style="width: 100%"
              @change="handleChange"
            >
              <a-select-option
                v-for="item in stationNameOptions"
                :key="item.stationId"
                :value="item.stationId"
                :label="item.stationName"
              >
                {{ item.stationName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="操作日期" name="operateDate">
            <a-date-picker
              v-model:value="formState.operateDate"
              style="width: 100%"
              format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD"
              @change="handleChange"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="操作类型" name="operateType">
            <a-select
              v-model:value="formState.operateType"
              placeholder="请选择操作类型"
              style="width: 100%"
              @change="handleChange"
            >
              <!-- <a-select-option value="1">类型1</a-select-option>
              <a-select-option value="2">类型2</a-select-option> -->

              <a-select-option
                v-for="item in operateList"
                :key="item.type"
                :value="item.type"
                :label="item.configName"
              >
                {{ item.configName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8" v-if="editData?.afterUpdate && editData?.beforeUpdate">
          <a-form-item label="操作对比" name="runDesc">
            <a-button
              type="link"
              @click="showComparisonModal"
              style="padding: 0"
              >表格对比</a-button
            >
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="操作日志" name="operateLog">
            <a-textarea
              v-model:value="formState.operateLog"
              placeholder="请输入操作日志"
              :rows="4"
            />
          </a-form-item>
          <a-form-item label="运行情况描述" name="runningDesc">
            <a-textarea
              v-model:value="formState.runningDesc"
              placeholder="请输入运行情况描述"
              :rows="4"
            />
          </a-form-item>
          <a-form-item label="待处理任务" name="pendingTask">
            <a-textarea
              v-model:value="formState.pendingTask"
              placeholder="请输入待处理任务"
              :rows="4"
            />
          </a-form-item>
          <a-form-item label="备注" name="remark">
            <a-textarea
              v-model:value="formState.remark"
              placeholder="请输入备注"
              :rows="4"
            />
          </a-form-item>
        </a-col>
      </a-form>
    </a-row>
  </a-modal>

  <!-- 表格对比弹窗 -->
  <ComparisonModal
    v-model:visible="comparisonModalVisible"
    :comparisonData="comparisonData"
  />
</template>

<script setup>

import { FAULT_REGISTRATION_TYPE } from "@/constants/faultRegistration.js"
import storage from "@/utils/storage"
import ComparisonModal from "./ComparisonModal.vue"

const $api = inject("$api")
const modelWidth = computed(() => (window.innerWidth > 1805 ? "65%" : "75%"))
const operateList = computed(() =>
  FAULT_REGISTRATION_TYPE.filter((e) => e.type > 3)
)
const userInf = storage.getItem("USER_INFO")

const props = defineProps({
  operationRecordVisible: {
    type: Boolean,
    default: false,
  },
  editData: {
    type: Object,
    default: () => ({}),
  },
  stationNameOptions: {
    type: Array,
    default: () => [],
  },
})
const modalTitle = computed(() =>
  props.editData?.id ? "编辑操作记录" : "新增操作记录"
)
const visible = ref(props.operationRecordVisible)
watch(
  () => props.operationRecordVisible,
  (val) => {
    visible.value = val
    if (val) {
      getLogTemplate()
      if (props.isEdit) {
        //form.value = props.rowData
      } else {
        //formRef.value?.resetFields()
      }
    }
  }
)
const emit = defineEmits(["update:operationRecordVisible", "success"])

const formRef = ref()
const confirmLoading = ref(false)

let formState = reactive({
  stationId: undefined,
  operateDate: undefined,
  operateType: undefined,
  runDesc: "",
  handleItem: "",
  remark: "",
})

const rules = {
  stationId: [{ required: true, message: "请选择电站" }],
  operateDate: [{ required: true, message: "请选择操作日期" }],
  operateType: [{ required: true, message: "请选择操作类型" }],
  operateLog: [{ required: true, message: "请输入操作日志" }],
}
//获取日志模版
const list = ref([])
const getLogTemplate = async (type) => {
  const res = await $api.faultConfigList({
    configType: 4,
  })
  if (res && res.code === 0) {
    list.value = res.data
  }
  console.log(list.value)
}
//设置操作日志
const userName = computed(() => userInf?.user_info?.uname)
const handleChange = () => {
  const item = list.value.find((e) => e.type === formState.operateType)
  if (item?.operateTemplate) {
    const selectedStation = props.stationNameOptions.find(
      (station) => station.stationId === formState.stationId
    )
    let template = item.operateTemplate

    // 替换操作时间
    template = template.replace(/【操作时间】/g, formState.operateDate || "")

    // 替换操作人
    template = template.replace(/【操作人】/g, userName.value || "")

    // 替换电站名称（支持两种格式：【X#】和【*#】）
    template = template.replace(/【X#】/g, selectedStation?.stationName || "")
    template = template.replace(/【\*#】/g, selectedStation?.stationName || "")

    formState.operateLog = template
  } else {
    formState.operateLog = ""
  }
}
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    confirmLoading.value = true

    const params = {
      ...formState,
    }
    if (props.editData?.id) {
      params.id = props.editData.id
    }

    let res = await $api.operateLogSave(params)
    if (res && res.code === 0) {
      message.success("保存成功")
      emit("success")
    }

    handleCancel()
  } catch (error) {
    console.error(error)
  } finally {
    confirmLoading.value = false
  }
}

const handleCancel = () => {
  formState = {
    stationId: undefined,
    operateDate: undefined,
    operateType: undefined,
    runDesc: "",
    handleItem: "",
    remark: "",
  }
  emit("update:operationRecordVisible", false)
}
// 表格对比弹窗相关
const comparisonModalVisible = ref(false)
const comparisonData = reactive({
  before: [],
  after: [],
})
// 监听编辑数据变化
watch(
  () => props.editData,
  (val) => {
    if (val) {
      if (val?.afterUpdate && val?.beforeUpdate) {
        comparisonData.before = JSON.parse(val.beforeUpdate)
        comparisonData.after = JSON.parse(val.afterUpdate)
      }
    }
    if (val?.id) {
      Object.assign(formState, val)
    }
  },
  { immediate: true }
)

// 显示表格对比弹窗
const showComparisonModal = () => {
  comparisonModalVisible.value = true
}
</script>
<style lang="less" scoped>
.mainTitle {
  margin-bottom: 30px;
}
.formInput,
.formSelect {
  width: 100%;
}
:deep(.ant-form-item) {
  margin-bottom: 20px;
}
</style>
>
